<template>
  <!-- 投顾管理 公有池 页面 -->
  <div class="investManage-page app-container">
    <div class="container">
      <div class="container-header">
        <div class="left">
          <div class="title">投顾管理-公有池</div>
          <el-form
            ref="searchDataForm"
            :inline="true"
            label-width="80px"
            :model="searchDataForm"
          >
            <el-form-item label="" prop="adviserName">
              <el-input
                v-model="searchDataForm.adviserName"
                size="small"
                clearable
                @keyup.enter.native="searchList"
                suffix-icon="el-icon-search"
                placeholder="请输入投顾名称"
                style="width: 220px;"
              ></el-input>
            </el-form-item>
            <el-form-item label="" prop="userName">
              <el-input
                v-model="searchDataForm.userName"
                size="small"
                clearable
                suffix-icon="el-icon-search"
                @keyup.enter.native="searchList"
                placeholder="请输入创建人"
                style="width: 220px;"
              ></el-input>
            </el-form-item>
            <el-form-item style="margin-left: 20px">
              <el-button size="small" class="bg-green" @click="searchList">
                查询
              </el-button>
              <el-button size="small" @click="searchResetForm">重置</el-button>
          </el-form-item>
          </el-form>
        </div>
        <div class="right-btn">
          <el-button
            v-if="userName === 'qyb'"
            type="primary"
            class="search-box"
            size="small"
            @click="handleUpdate()"
          >
            <i class="el-icon-plus el-icon--right"></i>
            添加投顾
          </el-button>
          <!-- <el-button type="primary" class="search-box" size="small" @click="uploadView = true">批量导入投顾</el-button>  -->
        </div>
      </div>
      <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list"
        stripe
        fit
        size="mini"
        @sort-change="sortCchange"
        :header-cell-style="{ color: '#333' }"
        style="width: 100%;"
      >
        <el-table-column
          type="index"
          label="序号"
          align="center"
          width="60"
          fixed
        ></el-table-column>
        <el-table-column
          prop="investName"
          label="投顾名称"
          min-width="240"
          fixed
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <!-- <span style="color: #4f95dd;cursor: pointer;" @click="goPolicyManageHandle(row.investName)">{{ row.investName }}</span> -->
            <span>{{ tooltipString(row.investName) }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="investContacts"
          label="联系人"
          min-width="130"
          sortable="custom"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="investMobile"
          label="手机号码"
          width="130"
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="investWechat"
          label="微信号"
          min-width="140"
          show-overflow-tooltip
          sortable="custom"
        ></el-table-column>
        <el-table-column
          prop="investEmail"
          label="邮箱"
          min-width="160"
          sortable="custom"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="investCreatedName"
          label="创建人"
          min-width="100"
          sortable="custom"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="investCommittime"
          label="成立日期"
          width="100"
          sortable="custom"
        >
          <template slot-scope="{ row }">
            <span>{{ row.investCommittime | parseTime }}</span>
          </template>
        </el-table-column>
        <el-table-column
          prop="investChannel"
          label="渠道来源"
          min-width="160"
          sortable="custom"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          prop="investRecommendReason"
          label="推荐理由"
          min-width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          v-if="userName === 'qyb'"
          fixed="right"
          label="操作"
          width="80"
        >
          <template slot-scope="{ row }">
            <el-button
              class="filter-item"
              size="mini"
              icon="el-icon-connection"
              @click="goPolicyManageHandle(row.investName, row.investId)"
            >
              下属策略
            </el-button>
            <el-button
              class="filter-item"
              size="mini"
              style="margin-left: 10px;"
              icon="el-icon-edit"
              @click="handleUpdate(row)"
            >
              编辑
            </el-button>
            <el-button
              class="filter-item"
              size="mini"
              style="margin-left: 10px;"
              icon="el-icon-delete"
              @click="deleteHandle(row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="listQuery.pageCurrent"
        :limit.sync="listQuery.limit"
        @pagination="getList"
      />

      <el-dialog
        title="批量导入投顾"
        :visible.sync="uploadView"
        :close-on-click-modal="false"
      >
        <div style="display: flex;">
          <el-upload
            class="search-box"
            action=""
            :before-upload="beforeUpload"
            :file-list="fileList"
          >
            <el-button
              class="upload-btn"
              type="primary"
              size="small"
              :icon="uploadBtnIcon"
            >
              {{ uploadBtnTxt }}
            </el-button>
          </el-upload>
          <el-button
            style="margin-left: 15px;"
            class="bg-green search-box download-btn"
            size="small"
            @click="downloadHandle"
          >
            下载模板
          </el-button>
        </div>
      </el-dialog>

      <el-dialog
        :title="textMap[dialogStatus]"
        :visible.sync="dialogFormVisible"
        :close-on-click-modal="false"
      >
        <el-form
          ref="dataForm"
          :rules="rules"
          :model="temp"
          label-position="right"
          label-width="80px"
          style="width: 500px; margin-left: 50px;"
        >
          <el-form-item label="投顾名称" prop="investName">
            <el-input v-model="temp.investName" placeholder="请输入投顾名称" />
          </el-form-item>
          <el-form-item label="联系人" prop="investContacts">
            <el-input
              v-model="temp.investContacts"
              placeholder="请输入联系人"
            />
          </el-form-item>
          <el-form-item label="手机号码" prop="investMobile">
            <el-input
              v-model.trim="temp.investMobile"
              placeholder="请输入手机号码"
            />
          </el-form-item>
          <el-form-item label="成立日期" prop="investCommittime">
            <el-date-picker
              v-model="temp.investCommittime"
              type="date"
              placeholder="请选择成立日期"
              style="width: 420px;"
            ></el-date-picker>
          </el-form-item>
          <el-form-item label="微信号" prop="investWechat">
            <el-input v-model="temp.investWechat" placeholder="请输入微信号" />
          </el-form-item>
          <el-form-item label="邮箱" prop="investEmail">
            <el-input v-model="temp.investEmail" placeholder="请输入邮箱" />
          </el-form-item>
          <el-form-item label="合作意向" prop="investType">
            <el-select
              v-model="temp.investType"
              placeholder="请选择合作意向"
              style="width: 420px;"
            >
              <el-option
                :label="item.name"
                :value="item.id"
                v-for="item in typeList"
                :key="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="渠道来源" prop="investChannel">
            <el-autocomplete
              v-model="temp.investChannel"
              :fetch-suggestions="querySearch"
              @select="handleSelect"
              style="width: 420px;"
              placeholder="请输入渠道来源"
            >
              <template slot-scope="{ item }">
                <div class="name">{{ item }}</div>
              </template>
            </el-autocomplete>
          </el-form-item>
          <el-form-item label="推荐理由" prop="investRecommendReason">
            <el-input
              v-model="temp.investRecommendReason"
              placeholder="请输入推荐理由"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogFormVisible = false">取消</el-button>
          <el-button
            type="primary"
            @click="dialogStatus === 'create' ? createData() : updateData()"
          >
            提交
          </el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import XLSX from 'xlsx'
import { debounce } from '@/utils/validate'
import Pagination from '@/components/Pagination'
import {
  fetchList,
  update,
  download,
  upload,
  addAdviser,
  deleteAdviser,
} from '@/api/investManage'
import { mapGetters } from 'vuex'
// import { getToken } from '@/utils/auth'
// import axios from 'axios'

export default {
  name: 'PublicInvest',
  components: { Pagination },
  data() {
    // var checkPhone = (rule, value, callback) => {
    //   const phoneReg = /^1[3|4|5|7|8][0-9]{9}$/
    //   if (!value) {
    //     return callback(new Error('电话号码必填'))
    //   }
    //   setTimeout(() => {
    //     // Number.isInteger是es6验证数字是否为整数的方法,但是我实际用的时候输入的数字总是识别成字符串
    //     // 所以在前面加了一个+实现隐式转换

    //     if (!Number.isInteger(+value)) {
    //       callback(new Error('请输入数字值'))
    //     } else {
    //       if (phoneReg.test(value)) {
    //         callback()
    //       } else {
    //         callback(new Error('电话号码格式不正确'))
    //       }
    //     }
    //   }, 100)
    // }
    // var checkEmail = (rule, value, callback) => {
    //   const mailReg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/
    //   if (!value) {
    //     // return callback(new Error('邮箱不能为空'))
    //     return callback()
    //   }
    //   setTimeout(() => {
    //     if (mailReg.test(value)) {
    //       callback()
    //     } else {
    //       callback(new Error('请输入正确的邮箱格式'))
    //     }
    //   }, 100)
    // }
    return {
      downloadModel_loading: false,
      total: 0,
      listLoading: false,
      searchDataForm: {},
      listQuery: {
        pageCurrent: 1,
        limit: 20,
      },
      strategyPool: 1, //公有池
      list: [],
      fileList: [],
      typeList: [
        { id: 1, name: 'MOM' },
        { id: 2, name: 'FOF' },
        { id: 3, name: '专户' },
        { id: 4, name: '其他' },
      ],
      investChannelList: ['朋友介绍', '期货公司', '网上搜索', '其他'],

      uploadBtnIcon: '',
      uploadBtnTxt: '导入excel',

      uploadView: false,

      temp: {
        investChannel: '',
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '添加',
      },
      rules: {
        investName: [
          { required: true, message: '投顾名称必填', trigger: 'change' },
        ],
        // investContacts: [{ required: true, message: '联系人必填', trigger: 'change' }],
        // investMobile: [{ validator: checkPhone, required: true, trigger: 'blur' }],
        // investEmail: [{ validator: checkEmail, trigger: 'blur' }],
        // investCommittime: [{ required: true, message: '成立日期必填', trigger: 'change' }]
      },
      orderInfo: {}, //排序
    }
  },
  created() {
    this.tempRoute = Object.assign({}, this.$route)
    this.$setTagsViewTitle(this.tempRoute, `投顾公有池`)
    this.getList()
  },
  activated() {
    if (this.$route.query.typePage === 'add') {
      this.getList()
    }
  },
  computed: {
    ...mapGetters(['userId', 'userName']),
    tooltipString: function() {
      return function(str) {
        if (str.length >= 30) {
          return str.substr(0, 30) + '...'
        }
        return str
      }
    },
  },
  methods: {
    sortCchange(column) {
      if (!column.order) {
        this.orderInfo = {}
      } else {
        this.orderInfo = {
          [column.prop]: column.order == 'ascending' ? 'asc' : 'desc',
        }
      }
      this.getList()
    },
    handleSelect(item) {
      this.temp.investChannel = item
    },
    querySearch(queryString, cb) {
      const restaurants = this.investChannelList
      const results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return restaurant.toLowerCase().indexOf(queryString.toLowerCase()) === 0
      }
    },
    goPolicyManageHandle(investName, investId) {
      this.$router.push({
        path: '/publicPolicy',
        query: {
          investName,
          investId,
        },
      })
    },
    downloadHandle() {
      download().then((res) => {
        const content = res
        const blob = new Blob([content])
        const fileName = '投顾模板.xlsx'
        if ('download' in document.createElement('a')) {
          // 非IE下载
          const elink = document.createElement('a')
          elink.download = fileName
          elink.style.display = 'none'
          elink.href = URL.createObjectURL(blob)
          document.body.appendChild(elink)
          elink.click()
          URL.revokeObjectURL(elink.href) // 释放URL 对象
          document.body.removeChild(elink)
        } else {
          // IE10+下载
          navigator.msSaveBlob(blob, fileName)
        }
      })
    },
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = row ? 'update' : 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    deleteHandle(row) {
      this.$confirm(`确认删除投顾名称【${row.investName}】此条数据？`, '提示', {
        type: 'warning',
      })
        .then((_) => {
          deleteAdviser({
            strategyPool: this.strategyPool,
            createdBy: this.userId,
            investId: row.investId,
          }).then((res) => {
            if (res.code == 0) {
              this.$notify({
                message: '操作成功',
                type: 'success',
                duration: 2000,
              })
              this.getList()
            }
          })
        })
        .catch((_) => {})
    },
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          addAdviser({
            strategyPool: this.strategyPool,
            ...this.temp,
            investCereatedby: this.userId,
          }).then((res) => {
            if (res.code == 0) {
              this.$notify({
                message: '修改成功',
                type: 'success',
                duration: 2000,
              })
              this.dialogFormVisible = false
              this.getList()
            }
          })
        }
      })
    },
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.temp.strategyPool = this.strategyPool
          const tempData = Object.assign({}, this.temp)
          update(tempData).then(() => {
            const index = this.list.findIndex(
              (v) => v.investId === this.temp.investId,
            )
            this.list.splice(index, 1, this.temp)
            this.dialogFormVisible = false
            this.$notify({
              message: '修改成功',
              type: 'success',
              duration: 2000,
            })
          })
        }
      })
    },
    beforeUpload(file) {
      this.uploadBtnTxt = '正在导入..'
      this.importDataBtnIcon = 'el-icon-loading'
      const fd = new FormData()
      fd.append('file', file)
      fd.append('userId', this.userId)
      // const upload_url = process.env.NODE_ENV === 'production' ? `${process.env.VUE_APP_BASE_API}/invest/adviser/upload` : '/api/invest/adviser/upload'
      // axios.post(upload_url, fd, {
      //   headers: {
      //     "token": getToken(),
      //     'Content-Type': 'multipart/form-data'
      //   }
      // }).then(() => {
      //   this.uploadBtnTxt = '导入excel'
      //   this.getList()
      // }, (res) => {
      //   this.uploadBtnTxt = '导入excel'
      //   this.$message({
      //     message: res.msg || '导入失败',
      //     type: 'error',
      //     duration: 3 * 1000
      //   })
      // })
      upload(fd).then(
        () => {
          this.uploadBtnTxt = '导入excel'
          this.$message({
            message: '导入成功',
            type: 'success',
            duration: 2 * 1000,
          })
          this.getList()
        },
        (res) => {
          this.uploadBtnTxt = '导入excel'
        },
      )

      // await this.readerData(file)

      // const res = await upload(fd)

      return false // 必要，阻止组件默认请求
    },
    readerData(rawFile) {
      return new Promise((resolve, reject) => {
        const reader = new FileReader()
        reader.onload = (e) => {
          const xlsxData = {}
          const xlsxHeader = {}
          const data = e.target.result
          const workbook = XLSX.read(data, { type: 'array' })
          // const firstSheetName = workbook.SheetNames[0]
          // const worksheet = workbook.Sheets[firstSheetName]
          // const header = this.getHeaderRow(worksheet)
          // const results = XLSX.utils.sheet_to_json(worksheet, {raw:false})

          workbook.SheetNames.forEach((item) => {
            xlsxData[item] = XLSX.utils.sheet_to_json(workbook.Sheets[item], {
              raw: false,
            })
            xlsxHeader[item] = this.getHeaderRow(workbook.Sheets[item])
          })

          resolve()
        }
        reader.readAsArrayBuffer(rawFile)
      })
    },
    getHeaderRow(sheet) {
      const headers = []
      const range = XLSX.utils.decode_range(sheet['!ref'])
      let C
      const R = range.s.r
      /* start in the first row */
      for (C = range.s.c; C <= range.e.c; ++C) {
        /* walk every column in the range */
        const cell = sheet[XLSX.utils.encode_cell({ c: C, r: R })]
        /* find the cell in the first row */
        let hdr = 'UNKNOWN ' + C // <-- replace with your desired default
        if (cell && cell.t) hdr = XLSX.utils.format_cell(cell)
        headers.push(hdr)
      }
      return headers
    },
    searchResetForm() {
      this.$refs.searchDataForm.resetFields()
      this.getList()
    },
    searchList() {
      this.listQuery.pageCurrent = 1
      debounce(this.getList, 300)()
    },
    getList() {
      this.listLoading = true
      fetchList({
        userId: this.userId,
        orderInfo: this.orderInfo,
        strategyPool: this.strategyPool,
        ...this.searchDataForm,
        ...this.listQuery,
      }).then((res) => {
        this.listLoading = false
        console.log('投顾管理', res)
        this.list = res.body.list
        this.total = res.body.total
        this.$nextTick(() => {
          this.$refs.multipleTable.doLayout()
        })
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>
